const {db} = require("../models/db");
// 获取树形表格的code
const setTreeTableCode = async (mod = '', formData, ctx) => {
    try {
        let pid = formData.pid ? formData.pid : null;
        let mode = null
        if(pid) {
            mode = await db.models[mod].findOne({
                where: {
                    pid
                },
                order: [['code', 'desc']]
            })
        }
        else {
            mode = await db.models[mod].findOne({
                where: {
                    tenantId: ctx.user.tenantId,
                    pid: 0
                },
                order: [['code', 'desc']]
            })
        }
        if (!pid) {
            if(mode) {
                formData.code = (parseInt(mode.code) + 1).toString()
            }
            else {
                formData.code = '100';
            }
        }
        else {
            if(mode) {
                formData.code = (parseInt(mode.code) + 1).toString()
            }
            else {
                let pidMode = await db.models[mod].findOne({
                    where: {id: pid}
                })
                formData.code = pidMode.code + '100'
            }
        }
    } catch (e) {
        console.log('save-err=', e)
    }
}

module.exports = {setTreeTableCode}